from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from time import sleep

def wait_for_element(xpath, timeout=30):
    return WebDriverWait(browser, timeout).until(EC.presence_of_element_located((By.XPATH, xpath)))

# 启动浏览器
path = 'chromedriver.exe'
browser = webdriver.Chrome(path)
browser.maximize_window()
browser.get("https://chat.deepseek.com/")

# 登录操作（账号密码登录）
wait_for_element('//*[@id="root"]/div/div/div[2]/div/div/div[2]/div[1]/div[1]/div[2]').click()
wait_for_element('//*[@id="root"]/div/div/div[2]/div/div/div[2]/div[1]/div[3]/div[1]/div/input').send_keys('18307056280')
browser.find_element(By.XPATH, '//*[@id="root"]/div/div/div[2]/div/div/div[2]/div[1]/div[4]/div[1]/div/input').send_keys('20191024lxl')
browser.find_element(By.XPATH, '//*[@id="root"]/div/div/div[2]/div/div/div[2]/div[1]/div[6]').click()
# 等待进入对话界面
sleep(5)
print("✅ 登录成功，开始与 DeepSeek 对话（输入 'exit' 退出）")

def send_message_and_get_reply(message):
    try:
        # 找到输入框并发送消息
        chatbox_xpath = '/html/body/div[1]/div/div/div[2]/div[3]/div/div/div[2]/div[2]/div/div/div[1]/textarea'
        chatbox = wait_for_element(chatbox_xpath)
        chatbox.clear()
        chatbox.send_keys(message)
        sleep(0.5)

        # 点击发送按钮
        send_button_xpath = '//*[@id="root"]/div/div/div[2]/div[3]/div/div/div[2]/div[2]/div/div/div[2]/div[3]/div[2]'
        send_btn = browser.find_element(By.XPATH, send_button_xpath)
        send_btn.click()
        sleep(1)
        # 等待按钮恢复可用状态（表示模型回复完成）
        WebDriverWait(browser, 60).until(
            lambda driver: send_btn.get_attribute("aria-disabled") == "true"
        )

        # 获取最新一条模型回复
        replies = browser.find_elements(By.CSS_SELECTOR,
            'div.markdown.prose.w-full.break-words.light > p')
        last_reply = replies[-1].text if replies else "[未能获取回复]"
        return last_reply
    except TimeoutException:
        return "[等待回复超时]"
    except Exception as e:
        return f"[出错] {e}"

# 交互式循环对话
while True:
    user_input = input("\n你：")
    if user_input.strip().lower() in ['exit', 'quit']:
        print("👋 已退出对话。")
        break

    reply = send_message_and_get_reply(user_input)
    print("DeepSeek：", reply)

# 关闭浏览器
browser.quit()
